package com.zat.mes.andrmes.dofun.system

import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.love.zywanandroid.retrofit.RetrofitManager
import com.love.zywanandroid.retrofit.api.ApiService
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.BaseResponse
import com.zat.mes.andrmes.data.ChaVerPicBean
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.main.MainActivity
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.retrofit.callback.MesCallBack
import com.zat.mes.andrmes.utils.GlideUtil
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_phone_ver.*
import kotlinx.android.synthetic.main.layout_title.*
import okhttp3.RequestBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Response

/**
 * 手机验证
 */
class PhoneVerActivity : BaseActivity() {

    var timer: MyCountDownTimer? = null
    var accessToken = ""
    var captchaToken = ""
    var empId = ""
    override fun init() {
        initView()
        initData()
    }

    private fun initView() {
        setContentView(R.layout.activity_phone_ver)
        tVtitle.text = getString(R.string.text_phone_check)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        ivPicVer.setOnClickListener {
            showLoading()
            getPic()
        }
        btnVer.setOnClickListener {
            if (TextUtils.isEmpty(etPhoneVer.text)) {
                showToast(getString(R.string.text_input_phone_no))
                return@setOnClickListener
            }
            if (etPhoneVer.text.length < 11) {
                showToast(getString(R.string.text_input_right_phone_no))
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(etPicVer.text)) {
                showToast(getString(R.string.text_input_captcha))
                return@setOnClickListener
            }
            showLoading()
            getMsCode()
        }

        btnLoginVer.setOnClickListener {

            if (TextUtils.isEmpty(etPhoneVer.text)) {
                showToast(getString(R.string.text_input_phone_no))
                return@setOnClickListener
            }
            if (etPhoneVer.text.length < 11) {
                showToast(getString(R.string.text_input_right_phone_no))
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(etPicVer.text)) {
                showToast(getString(R.string.text_input_captcha))
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(etCodeVer.text)) {
                showToast(getString(R.string.text_input_vercode))
                return@setOnClickListener
            }
            showLoading()
            postUcc()
        }
    }

    private fun initData() {
        empId = intent.getStringExtra("empId")
        accessToken = intent.getStringExtra("accessToken")
        getPic()
        showLoading()

    }


    /**
     * 获取图形
     */
    private fun getPic() {
        RetrofitManager.apiService(ApiService::class.java)
            .getCaptcha(accessToken)
            .enqueue(object : MesCallBack<BaseResponse<String>>() {
                override fun onSuccessful(
                    call: Call<BaseResponse<String>>?,
                    response: Response<BaseResponse<String>>?
                ) {
                    closeLoading()
                    val result = response?.body()?.result
                    val chaVerPicBean = Gson().fromJson<ChaVerPicBean>(
                        result,
                        ChaVerPicBean::class.java
                    )
                    if (chaVerPicBean != null) {
                        Glide.with(this@PhoneVerActivity)
                            .load(GlideUtil.stringToBitmap(chaVerPicBean.captcha_image))
                            .into(ivPicVer)
                        captchaToken = chaVerPicBean.captcha_token
                    }

                }

            })
    }

    /**
     * 获取短信验证码
     */
    private fun getMsCode() {
        RetrofitManager.apiService(ApiService::class.java)
            .getMsCode(
                accessToken,
                etPhoneVer.text.toString(),
                captchaToken,
                etPicVer.text.toString()
            )
            .enqueue(object : MesCallBack<BaseResponse<String>>() {
                override fun onSuccessful(
                    call: Call<BaseResponse<String>>?,
                    response: Response<BaseResponse<String>>?
                ) {
                    closeLoading()
                    try {
                        val result = response?.body()?.result
                        val json = JSONObject(result)
                        val success = json.optString("success")
                        val time = json.optInt("delay", 0)
                        if ("true".equals(success) && time != 0) {
                            timer =
                                MyCountDownTimer(time * 1000L, 1000, btnVer, this@PhoneVerActivity)
                            timer?.start()
                            return
                        }
                        val errorMsg = json.optString("error_description")
                        if (!TextUtils.isEmpty(errorMsg)) {
                            showToast(errorMsg)
                        }
                    } catch (e: Exception) {

                    }


                }

            })
    }

    /**
     * 注册
     */

    private fun postUcc() {
        val jsonObject = JSONObject()
        jsonObject.put("access_token", accessToken)
        jsonObject.put("username", etPhoneVer.text.toString())
        jsonObject.put("empId",empId)
        jsonObject.put("verificationCode", etCodeVer.text.toString())
        val requestBody: RequestBody =
            RequestBody.create(RetrofitManager.JOSNTYPE, jsonObject.toString())
        RetrofitManager.apiService(ApiService::class.java)
            .signUpUcc(requestBody)
            .enqueue(object : MesCallBack<BaseResponse<String>>() {
                override fun onSuccessful(
                    call: Call<BaseResponse<String>>?,
                    response: Response<BaseResponse<String>>?
                ) {
                    try {
                        val result = response?.body()?.result
                        val json = JSONObject(result)
                        val access_token = json.optString("access_token")
                        if (!TextUtils.isEmpty(access_token)) {
//                            postLoginFirst()
                            val loginResultBean = Gson().fromJson(
                                PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
                                LoginResultBean::class.java
                            )
                            loginResultBean?.isfirst = "2"
                            //保存登录后人员企业等信息
                            PreferencesUtil.saveValue(
                                CompanionType.LOGIN_RESULT,
                                Gson().toJson(loginResultBean)
                            )
                            startBaseActivity(
                                Intent(
                                    this@PhoneVerActivity,
                                    MainActivity::class.java
                                )
                            )
                            finish()
                            return
                        }else{
                            closeLoading()
                        }
                        val errorMsg = json.optString("error_description")
                        if (!TextUtils.isEmpty(errorMsg)) {
                            showToast(errorMsg)
                        }
                    } catch (e: java.lang.Exception) {

                    }

                }

            })
    }

    /**
     * 修改首次登录
     */
    private fun postLoginFirst() {
        val jsonObject = JSONObject()
        jsonObject.put("access_token", accessToken)
        jsonObject.put("username", etPhoneVer.text.toString())
        jsonObject.put("empid", empId)
        val requestBody: RequestBody =
            RequestBody.create(RetrofitManager.JOSNTYPE, jsonObject.toString())
        RetrofitManager.apiService(ApiService::class.java)
            .upLoginFirst(requestBody)
            .enqueue(object : MesCallBack<BaseResponse<String>>() {
                override fun onSuccessful(
                    call: Call<BaseResponse<String>>?,
                    response: Response<BaseResponse<String>>?
                ) {
                    closeLoading()
                    if (response?.body()?.success !== null) {
                        if (response?.body()?.success!!) {
                            val loginResultBean = Gson().fromJson(
                                PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
                                LoginResultBean::class.java
                            )
                            loginResultBean?.isfirst = "2"
                            //保存登录后人员企业等信息
                            PreferencesUtil.saveValue(
                                CompanionType.LOGIN_RESULT,
                                Gson().toJson(loginResultBean)
                            )
                            startBaseActivity(
                                Intent(
                                    this@PhoneVerActivity,
                                    MainActivity::class.java
                                )
                            )
                            finish()
                        } else {
                            showToast(response?.body()?.message)
                        }
                    } else {
                        showToast(response?.body()?.message)
                    }
                }

            })
    }

    override fun onDestroy() {
        clearTimer()
        super.onDestroy()
    }
    /**
     *清除 timer
     */
    private fun clearTimer() {

        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
    }

    /**
     * 倒计时
     */
    class MyCountDownTimer(
        millisInFuture: Long,
        countDownInterval: Long,
        btnVer: TextView,
        context: Context
    ) : CountDownTimer(millisInFuture, countDownInterval) {
        val btnVer = btnVer
        val context = context
        override fun onFinish() {
            btnVer.setText(context.getString(R.string.text_vercode_agin));
            btnVer.setClickable(true);
            btnVer.setBackgroundResource(R.drawable.bg_phone_ver)
            btnVer.setTextColor(ContextCompat.getColor(context, R.color.color_white))
        }

        override fun onTick(millisUntilFinished: Long) {
            btnVer.setClickable(false)
            btnVer.setText((millisUntilFinished / 1000).toString() + "秒");
            btnVer.setBackgroundResource(R.drawable.bg_phone_ver_un)
            btnVer.setTextColor(ContextCompat.getColor(context, R.color.color_text_grey))
        }

    }


}
